<?php

namespace app\admin\controller\general;

use app\admin\model\Goods as GoodsM;
use app\admin\validate\Goods as GoodsV;
use app\common\controller\Backend;
use fast\Tree;
use think\Cache;

/**
 * 达人商品管理
 *
 * @icon   fa fa-list
 * @remark 规则通常对应一个控制器的方法,同时左侧的菜单栏数据也从规则中体现,通常建议通过控制台进行生成规则节点
 */
class Goods extends Backend
{

    /**
     * @var \app\admin\model\Goods
     */
    protected $model = null;
    protected $rulelist = [];
    protected $searchFields = 'id,title';

    public function _initialize()
    {
        parent::_initialize();
        // if (!$this->auth->isSuperAdmin()) {
        //     $this->error(__('Access is allowed only to the super management group'));
        // }
        $this->model = model('Goods');

        $expertLevelList = [];
        $expertLevelList["1"] = "一星达人";
        $expertLevelList["2"] = "二星达人";
        $expertLevelList["3"] = "三星达人";
        $this->assignconfig('expertLevelList', $expertLevelList);


        $positionList = [];
        $positionList["1"] = "推荐人";
        $positionList["2"] = "公司微小店";
        $positionList["3"] = "9代级别";

        $this->assignconfig('positionList', $positionList);

        
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $order_map = [
                "expert_level asc",
                "weigh asc",
                "id DESC"
            ];

            $list = $this->model
                ->where($where)
                ->order($order_map)
                ->paginate($limit);

            $list_info = $list->toArray();
            $total = $list_info["total"];
            $list = $list_info["data"];
            // exit(print_r($list));
            if ($list) {

                $category_ids = array_unique(array_column($list, "category_id"));
                // exit(print_r($subject_class_ids));

                $article_category_list = db("article_category")->whereIn("id", $category_ids)->field("id,title")->select();
                // exit(print_r($subject_class_list));
                foreach ($list as $key => $val) {
                    $list[$key]["category"] = "";
                    foreach ($article_category_list as $key2 => $val2) {
                        if ($val2["id"] == $val["category_id"]) {
                            $list[$key]["category"] = $val2["title"];
                        }
                    }
                }
                // exit(print_r($list));
            }

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add($ids = null)
    {

        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post("row/a", []);
            if ($params) {
                $admin = $this->auth->getUserInfo();
                $params["admin_id"] = $admin["id"];
                $result = $this->model->validate()->save($params);
                if ($result === false) {
                    $this->error($this->model->getError());
                }
                $this->success();
            }
            $this->error();
        }


        $expertLevelList = [];
        $expertLevelList["1"] = "一星达人";
        $expertLevelList["2"] = "二星达人";
        $expertLevelList["3"] = "三星达人";
        $this->view->assign('expertLevelList', build_select('row[expert_level]', $expertLevelList, "0", ['class' => 'form-control selectpicker']));


        $positionList = [];
        $positionList["1"] = "推荐人";
        $positionList["2"] = "公司微小店";
        $positionList["3"] = "9代级别";
        $this->view->assign('positionList', build_select('row[position]', $positionList, "0", ['class' => 'form-control selectpicker']));


        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post("row/a", []);
            if ($params) {

                $admin = $this->auth->getUserInfo();
                $params["admin_id"] = $admin["id"];

                $result = $row->validate()->save($params);
                if ($result === false) {
                    $this->error($row->getError());
                }
                $this->success();
            }
            $this->error();
        }
        $this->view->assign("row", $row);


        $expertLevelList = [];
        $expertLevelList["1"] = "一星达人";
        $expertLevelList["2"] = "二星达人";
        $expertLevelList["3"] = "三星达人";
        $this->view->assign('expertLevelList', build_select('row[expert_level]', $expertLevelList, $row["expert_level"], ['class' => 'form-control selectpicker']));

        $positionList = [];
        $positionList["1"] = "推荐人";
        $positionList["2"] = "公司微小店";
        $positionList["3"] = "9代级别";
        $this->view->assign('positionList', build_select('row[position]', $positionList, $row["position"], ['class' => 'form-control selectpicker']));


        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            // \think\Hook::add('upload_delete', function ($params) {
            //     $coverfile = ROOT_PATH . '/public' . $params['cover'];
            //     if (is_file($coverfile)) {
            //         @unlink($coverfile);
            //     }
            // });
            $list = $this->model->where('id', 'in', $ids)->select();
            foreach ($list as $row) {
                // \think\Hook::listen("upload_delete",  $row);
                $row->delete();
            }
            $this->success();
        }
        $this->error();
    }

    /**
     * 商品绑定到用户
     */
    public function bind($gids)
    {
        if ($this->request->isPost()) {
            $userids = $this->request->post("userids");
            $userids_array = explode(",", trim($userids, ","));
            $gids_array = explode(",", trim($gids, ","));

            foreach ($userids_array as $userid) {
                foreach ($gids_array as $gid) {
                    $item = [
                        "user_id" => $userid,
                        "goods_id" => $gid,
                    ];
                    db("expert_goods")->where("goods_id", $gid)->where("user_id", $userid)->delete();
                    db("expert_goods")->insert($item);
                }
            }
            $this->success("绑定成功");
        }

        $this->assignconfig("gids", $gids);

        // $rows = db("goods")->whereIn("id", $gids)->select();
        // // exit(print_r($rows));
        // $this->view->assign("rows", $rows);
        return $this->view->fetch();
    }


    /**
     * 复制商品
     */
    public function copy_goods($ids)
    {

        $goods = db("goods")->where("id", $ids)->find();
        if (!$goods) {
            $this->error("数据不存在");
        }
        $result = db("goods")->insert([
            "admin_id" => $goods["admin_id"],
            "title" => $goods["title"],
            "cover" => $goods["cover"],
            "weigh" => $goods["weigh"],
            "createtime" => $goods["createtime"],
            "updatetime" => $goods["updatetime"],
            "price" => $goods["price"],
            "expert_level" => $goods["expert_level"],
            "position" => $goods["position"],
        ]);
        if ($result == false) {
            $this->error("复制失败");
        }

        $this->success("复制成功");
    }



    /**
     * 商品已绑定的用户
     */
    public function bound_user()
    {
        $gid = $this->request->param("ids");
        $this->assignconfig("gid", $gid);
        return $this->view->fetch();
    }

    /**
     * 商品已绑定的用户
     */
    public function bound_user_list()
    {
        $gid = $this->request->param("gid");
        $search = $this->request->param("search");
        $limit = $this->request->param("limit");

        $map = [];
        $map["eg.goods_id"] = $gid;
        if ($search) {
            $map["u.username|u.nickname|u.mobile|u.unique_id"] = ["like", "%" . $search . "%"];
        }

        $list = db("expert_goods as eg")
            ->join("user user", "user.id = eg.user_id", "LEFT")
            ->join('user u2', "user.parent_user_id=u2.id", "LEFT")
            ->where($map)
            ->field("user.*,eg.id,u2.username as parent_user_username,u2.mobile as parent_user_mobile")
            ->paginate($limit);

        // exit(db()->getLastSql());
        $list_info = $list->toArray();
        $total = $list_info["total"];
        $list = $list_info["data"];
        // exit(print_r($list));

        foreach ($list as $k => $v) {
            // exit(print_r($v));
            $list[$k]["avatar"] = $v["avatar"] ? cdnurl($v["avatar"], true) : letter_avatar($v["nickname"]);
            unset($list[$k]["password"]);
            unset($list[$k]["salt"]);
        }

        $result = array("total" => $total, "rows" => $list);

        return json($result);
    }


    /**
     * 删除商品已绑定的用户
     */
    public function bound_user_drop($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            //删除关联
            db("expert_goods")->whereIn("id", $ids)->delete();
            $this->success("删除成功");
        }
        $this->error();
    }
}
